<?php
namespace app\app\controller\v1;
use app\app\Appbase;

class Lottery extends Appbase 
{
	
	/**
	* 获取活动信息
	* /app/v1/lottery/getInfo
	* 不需要登录 
	* @is_need_login true
	*/
	public function getInfo($lottery_sid=0,$latitude="",$longitude=""){
		$uid = request()->userId;
		$shop_id = request()->userInfo['shop_id'];
				
		//添加 局域限制
		if($latitude && $longitude){
			$model = model('Lottery'); 
			$model = $model->where('is_enable',1);
			$model = $model->where('is_del',0);
			$model = $model->field("ranges,latitude");
			$model = $model->field("ROUND(
		        6378.138 * 2 * 10000 * ASIN(
		            SQRT(
		                POW( SIN( ( $latitude * PI() / 180 - latitude * PI() / 180 ) / 2 ),2) 
		                + COS( $latitude * PI() / 180) * COS(latitude * PI() / 180) 
		                * POW( SIN(  ( $longitude * PI() / 180 - longitude * PI() / 180 ) / 2), 2)
		            )
		        ) / 10000
		  	,1) as distance");
			$lottery = $model->find();
			if($lottery['latitude'] && $lottery['distance'] > $lottery['ranges'] ){
				return $this->ReError("您不在可参加活动的区域！");	
			}
		}
		
		try {
			//TODO 活动信息
	        $activityInfo =   model('Lottery')->getActivity($uid,$shop_id);
			//TODO 中奖名单
	        $prizeList =  model('LotteryGetUser')->getList(0,$activityInfo->id,1,8);
	        
			//返回
			return $this->ReSucess(compact('activityInfo','prizeList') );	
			
		} catch (Exception $e) {
			throw new \think\Exception( $e );
		}
	}
	
	
	/**
	* 开始抽奖 
	* /app/v1/lottery/luckDraw
	* 不需要登录 
	* @is_need_login true
	*/
	public function luckDraw($id){
		
		if(empty($id)) return $this->ReError('活动id不能为空！');
		
		$uid =  request()->userId;
		$shop_id = request()->userInfo['shop_id'];
		
		try {
			//TODO 活动信息
	        $activityInfo =   model('Lottery')->getActivity($uid,$shop_id,$id);
			if(!$activityInfo){
				return $this->ReError('活动不存在！');
			}
			if($activityInfo['states'] != '进行中'){
				return $this->ReError( $activityInfo['states'] );
			}
			if($activityInfo['chanceNum'] < 1){
				return $this->ReError('抽奖次数已经用完！');
			}
			if($activityInfo['userPrizeNum'] >= $activityInfo['num_upper']){
				return $this->ReError('该活动您的抽奖次数已达上限！');
			}
			
			//TODO 开始抽奖
			$result =   model('Lottery')->luckDraw($uid,$activityInfo->id);
			if($result === false){
				return $this->ReError();
			}
			return $this->ReSucess($result);	
			
		} catch (\Exception $e) {
			throw new \think\Exception( $e );
		}
	}
	
	/**
	* 中奖日志 
	* /app/v1/lottery/prizeLog
	* 不需要登录 
	* @is_need_login true
	*/
	public function prizeLog($id){
		if(empty($id)){
			return $this->ReError('活动id不能为空！');
		}
		$uid =  request()->userId;
		try {
			$result =   model('LotteryGetUser')->getList($uid,$id,1,30);
			return $this->ReSucess($result);	
		} catch (Exception $e) {
			throw new \think\Exception( $e );
		}
	}
	
	
}



